<template>
  <div class="app-container">
    <div class="app-container-flex">
      <div class="left-container">
        <div class="left-container-header border-style-bottom">
          <el-button
            :plain="true"
            :disabled="state.saveBtn"
            @click="addMenu('ruleForm')"
            >{{ $t('btn_add') }}</el-button
          >
          <el-button
            :plain="true"
            :disabled="state.deleteBtn"
            @click="deleteMenu"
            >{{ $t('btn_delete') }}</el-button
          >
        </div>
        <div class="left-container-main main-flex">
          <el-tree
            ref="menuTree"
            :data="state.menuList"
            :draggable="true"
            highlight-current
            :props="state.defaultProps"
            node-key="id"
            :default-expand-all="false"
            :default-expanded-keys="['-1']"
            :expand-on-click-node="true"
            @node-click="handleNodeClick"
          />
        </div>
      </div>
      <div class="right-container">
        <div class="layui-card-body">
          <div class="layui-btn-container border-style-bottom">
            <el-button
              :plain="true"
              :disabled="state.validate"
              @click="_updateMenu('ruleForm')"
              >{{ $t('btn_save') }}</el-button
            >
          </div>
          <div>
            <el-form
              ref="ruleForm"
              :model="state.menuDetailData"
              :rules="state.rules"
              label-width="100px"
              class="paddingBox formBox flex_wrap_start_start"
            >
              <el-form-item :label="$t('parent_menu')" prop="parentName">
                <el-input
                  v-model.trim="state.menuDetailData.parentName"
                  maxlength="50"
                  :disabled="true"
                  @input="(e) => (state.menuDetailData.parentName = validSe(e))"
                />
              </el-form-item>
              <el-form-item :label="$t('menu_name')" prop="name">
                <el-input
                  v-model.trim="state.menuDetailData.name"
                  :disabled="
                    state.checkedMenuId === '-1' ||
                    state.menuDetailData.code === 'dashboard' ||
                    state.menuDetailData.code === 'app' ||
                    state.menuDetailData.code === 'pda'
                  "
                  maxlength="50"
                  @input="(e) => (state.menuDetailData.name = validSe(e))"
                />
              </el-form-item>
              <el-form-item :label="$t('menu_code')" prop="code">
                <el-input
                  v-model.trim="state.menuDetailData.code"
                  :disabled="
                    state.checkedMenuId === '-1' ||
                    state.menuDetailData.code === 'dashboard' ||
                    state.menuDetailData.code === 'app' ||
                    state.menuDetailData.code === 'pda'
                  "
                  maxlength="50"
                  @input="(e) => (state.menuDetailData.code = validSe(e))"
                />
              </el-form-item>
              <el-form-item :label="$t('source_code')" prop="resourceCode">
                <el-input
                  v-model.trim="state.menuDetailData.resourceCode"
                  :disabled="
                    state.checkedMenuId === '-1' ||
                    state.menuDetailData.code === 'dashboard' ||
                    state.menuDetailData.code === 'app' ||
                    state.menuDetailData.code === 'pda'
                  "
                  maxlength="50"
                  @input="
                    (e) => (state.menuDetailData.resourceCode = validSe(e))
                  "
                />
              </el-form-item>
              <el-form-item :label="$t('menu_icon')" prop="icon">
                <icons-dialog
                  v-if="state.menuDetailData.menuType === 0"
                  :modelValue="state.menuDetailData.icon"
                  :disabled="
                    state.checkedMenuId === '-1' ||
                    state.menuDetailData.code === 'dashboard' ||
                    state.menuDetailData.code === 'app' ||
                    state.menuDetailData.code === 'pda'
                  "
                  @returnBack="returnBackIcons"
                />
                <el-input
                  v-if="
                    state.menuDetailData.menuType === 1 ||
                    state.menuDetailData.menuType === 2
                  "
                  v-model="state.menuDetailData.icon"
                  :disabled="
                    state.checkedMenuId === '-1' ||
                    state.menuDetailData.code === 'dashboard' ||
                    state.menuDetailData.code === 'app' ||
                    state.menuDetailData.code === 'pda'
                  "
                ></el-input>
              </el-form-item>
              <el-form-item :label="$t('sort')" prop="sort">
                <el-input-number
                  v-model="state.menuDetailData.sort"
                  style="width: 100%"
                  :disabled="
                    state.checkedMenuId === '-1' ||
                    state.menuDetailData.code === 'dashboard' ||
                    state.menuDetailData.code === 'app' ||
                    state.menuDetailData.code === 'pda'
                  "
                  controls-position="right"
                  :max="999999"
                  :min="0"
                />
              </el-form-item>
              <el-form-item :label="$t('status')" prop="status">
                <ModelRadio
                  v-model="state.menuDetailData.status"
                  :disabled="
                    state.menuDetailData.code === 'menuManage' ||
                    state.menuDetailData.id === 5 ||
                    state.menuDetailData.code === 'dashboard' ||
                    state.menuDetailData.code === 'app' ||
                    state.menuDetailData.code === 'pda' ||
                    state.checkedMenuId === '-1'
                  "
                  type-code="new_enabled_type"
                />
              </el-form-item>
              <el-form-item :label="$t('display_status')" prop="displayStatus">
                <ModelRadio
                  v-model="state.menuDetailData.displayStatus"
                  :disabled="
                    state.menuDetailData.code === 'menuManage' ||
                    state.menuDetailData.id === 5 ||
                    state.menuDetailData.code === 'dashboard' ||
                    state.menuDetailData.code === 'app' ||
                    state.menuDetailData.code === 'pda' ||
                    state.checkedMenuId === '-1'
                  "
                  type-code="hidden_type"
                />
              </el-form-item>
              <el-form-item :label="$t('menu_link')" prop="url">
                <el-input
                  v-model.trim="state.menuDetailData.url"
                  :disabled="
                    state.checkedMenuId === '-1' ||
                    state.menuDetailData.code === 'dashboard' ||
                    state.menuDetailData.code === 'app' ||
                    state.menuDetailData.code === 'pda'
                  "
                  maxlength="200"
                  @input="(e) => (state.menuDetailData.url = validSe(e))"
                />
              </el-form-item>
              <el-form-item :label="$t('source_param')" prop="params">
                <el-input
                  v-model.trim="state.menuDetailData.params"
                  :disabled="
                    state.checkedMenuId === '-1' ||
                    state.menuDetailData.code === 'dashboard' ||
                    state.menuDetailData.code === 'app' ||
                    state.menuDetailData.code === 'pda'
                  "
                  maxlength="50"
                  @input="(e) => (state.menuDetailData.params = validSe(e))"
                />
              </el-form-item>
              <el-form-item
                class="not-br textaea"
                :label="$t('desc')"
                prop="desc"
              >
                <el-input
                  v-model.trim="state.menuDetailData.desc"
                  :disabled="state.checkedMenuId === '-1'"
                  type="textarea"
                  rows="1"
                  maxlength="200"
                  :placeholder="$t('err_menu_desc')"
                  @input="(e) => (state.menuDetailData.desc = validSe(e))"
                />
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div
          v-show="
            state.addOrUpdate != 'add' &&
            state.checkedMenuId !== '-1' &&
            state.checkedMenuCode !== 'app' &&
            state.checkedMenuCode !== 'pda'
          "
          class="layui-card-body"
        >
          <div class="opt-header border-style-bottom">
            <el-button
              :plain="true"
              :disabled="state.addBtn"
              @click="addResources(undefined)"
              >{{ $t('btn_add') }}</el-button
            >
            <el-button
              :plain="true"
              :disabled="state.electRows && state.electRows.length <= 0"
              @click="deleteRosources(undefined)"
              >{{ $t('btn_delete') }}</el-button
            >
          </div>
          <el-table
            ref="resourceTable"
            :data="state.resourceList"
            border
            header-row-class-name="tableHeader"
            style="width: 100%"
            :highlight-current-row="true"
            @selection-change="listSelect"
          >
            <el-table-column type="selection" align="center" />
            <el-table-column
              prop="name"
              align="center"
              :label="$t('operation_name')"
              show-overflow-tooltip
            />
            <el-table-column
              prop="code"
              align="center"
              :label="$t('operation_code')"
              show-overflow-tooltip
            />
            <el-table-column
              prop="type"
              align="center"
              :label="$t('source_type')"
              show-overflow-tooltip
            />
            <el-table-column
              prop="path"
              align="center"
              label="路由路径"
              show-overflow-tooltip
            />
            <el-table-column
              prop="resourceCode"
              align="center"
              label="组件名称"
              show-overflow-tooltip
            />
            <el-table-column
              prop="remark"
              align="center"
              :label="$t('desc')"
              show-overflow-tooltip
            />
            <el-table-column align="center" :label="$t('operation')" width="90">
              <template v-slot="scope">
                <a class="actionBtn" @click="addResources(scope.row)">{{
                  $t('btn_edit')
                }}</a>
                <a class="actionBtn" @click="deleteRosources(scope.row)">{{
                  $t('btn_delete')
                }}</a>
                <a
                  v-if="!!scope.row.isSelectPrintDialogVisible"
                  class="actionBtn"
                  @click="selectPrintTemplateRosources(scope.row)"
                  >{{ $t('btn_select_print_template') }}</a
                >
              </template>
            </el-table-column>
          </el-table>
          <!-- 新增修改资源 -->
          <add-edit
            :table-row="state.tableRow"
            :visible="state.dialogVisible"
            @callback="diaLogeCallback"
          />
          <PrintTemplateDialog
            v-if="state.isSelectPrintDialogVisible"
            v-model:query="state.querySelectedResource"
            v-model:show-dialog="state.isSelectPrintDialogVisible"
            @callback="onSelectPrintTemplateCallback"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup name="menu">
import AddEdit from './AddEdit.vue'
import PrintTemplateDialog from './view/PrintTemplateDialog.vue'
import {
  getMenusTree,
  createMenu,
  updateMenu,
  deleteMenus,
  getMenuDetail,
  getResourcesAll,
  deleteResources,
} from '@/api/base.js'
import ModelRadio from '@/components/ModelRadio'
import iconsDialog from './view/iconsDialog'

const { proxy } = getCurrentInstance()
const handleClosePrintTemplate = () => {
  console.log('//// data handleClosePrintTemplate')
}
const state = reactive({
  status: '',
  resourcesPanelShow: false,
  isSelectPrintDialogVisible: false,
  printTemplateDialogInfo: {
    title: '设置默认打印模板',
    btLoading: false,
    btList: [
      { label: '关闭', event: handleClosePrintTemplate, show: true },
      {
        label: '保存',
        type: 'primary',
        disabled: true,
        event: savePrintTemplate,
        show: true,
      },
    ],
  },
  deleteBtn: true,
  addBtn: true,
  saveBtn: true,
  validate: true,
  dialogVisible: false,
  addOrUpdate: 'update',
  menuDetailData: {},
  nodeId: {},
  selectRows: [],
  formBoxHeight: '',
  rules: {},
  menuList: [
    {
      name: '综合管理平台',
      id: '-1',
      menuType: 0,
      children: [],
    },
  ],
  defaultProps: {
    children: 'children',
    label: 'name',
  },
  tableRow: {},
  resourceList: [],
  height: 800,
  querySelectedResource: {},
  checkedMenuId: '-1',
  checkedMenuCode: 'app',
})

state.rules = {
  name: [
    { required: true, message: proxy.$t('null_menu_name'), trigger: 'blur' },
  ],
  sort: [
    { required: true, message: proxy.$t('null_sort_id'), trigger: 'blur' },
    { type: 'number', message: proxy.$t('null_number'), trigger: 'change' },
  ],
  code: [
    { required: true, message: proxy.$t('null_menu_code'), trigger: 'blur' },
  ],
  resourceCode: [
    {
      required: true,
      message: proxy.$t('null_source_code'),
      trigger: 'blur',
    },
  ],
}
onMounted(() => {
  getNavList()
})

function returnBackIcons(val) {
  state.menuDetailData.icon = val
}
function savePrintTemplate() {
  console.log('//// data savePrintTemplate')
}
function onSelectPrintTemplateCallback(data) {
  if (data) {
    state.isSelectPrintDialogVisible = false
  }
}
function selectPrintTemplateRosources(row) {
  state.isSelectPrintDialogVisible = true
  state.querySelectedResource = {
    id: row.id,
  }
}
function diaLogeCallback(data) {
  state.dialogVisible = false
  if (data) {
    loadResource(data)
  }
}
function deleteRosources(row) {
  const ids = []
  if (row && row.id) {
    ids.push(row.id)
  } else {
    state.selectRows.forEach((item) => {
      ids.push(item.id)
    })
  }
  if (!ids.length) {
    proxy.$message({
      type: 'warning',
      duration: 1500,
      message: '请选择数据',
    })
    return
  }
  proxy
    .$confirm(proxy.$t('confirm'), proxy.$t('notice'), {
      confirmButtonText: proxy.$t('btn_confirm'),
      cancelButtonText: proxy.$t('btn_cancel'),
      type: 'warning',
    })
    .then(() => {
      deleteResources(ids).then((resp) => {
        if (resp) {
          loadResource(state.menuNodeId)
        }
      })
    })
}
function listSelect(rows) {
  state.selectRows = rows
}
function deleteMenu() {
  //菜单删除

  let item = proxy.$refs.menuTree.getCurrentNode()
  proxy
    .$confirm(proxy.$t('menu_confirm'), proxy.$t('notice'), {
      confirmButtonText: proxy.$t('btn_confirm'),
      cancelButtonText: proxy.$t('btn_cancel'),
      type: 'warning',
    })
    .then(() => {
      deleteMenus([item.id]).then((resp) => {
        if (resp) {
          getNavList()
          state.validate = false
          state.checkedMenuId = '-1'
          state.checkedMenuCode = 'app'
          state.menuDetailData = {
            parentId: parent.id,
            parentName: parent.name,
            sort: 0,
          }
        }
      })
    })
}
function addMenu() {
  //添加菜单
  state.addOrUpdate = 'add'
  let parent = proxy.$refs.menuTree.getCurrentNode()
  state.validate = false
  state.checkedMenuId = ''
  state.checkedMenuCode = ''
  state.menuDetailData = {
    parentId: parent.id,
    parentName: parent.name,
    sort: 0,
    menuType: parent.menuType,
  }
}
function _updateMenu(formName) {
  //更新or添加菜单信息
  proxy.$refs[formName].validate((valid) => {
    if (valid) {
      const api = state.addOrUpdate === 'update' ? updateMenu : createMenu
      api(state.menuDetailData).then((resp) => {
        if (resp && resp.success) {
          if (state.menuDetailData.status === 1) {
            state.menuDetailData = {}
            state.resourcesPanelShow = false
          } else {
            state.validate = false
            state.checkedMenuId = '-1'
            state.checkedMenuCode = 'app'
            state.menuDetailData = {
              parentId: parent.id,
              parentName: parent.name,
              sort: 0,
            }
          }
          getNavList()
        }
      })
    } else {
      return false
    }
  })
}
function getNavList() {
  //获取菜单树

  getMenusTree().then((resp) => {
    if (resp) {
      state.menuList[0].children = resp.data
    }
  })
}
function addResources(row) {
  //权限设置
  state.dialogVisible = true
  if (row) {
    state.tableRow = { ...row }
  } else {
    state.tableRow = {
      ...state.nodeId,
      sort: state.resourceList.length + 1,
    }
  }
}
function loadResource(menuId = undefined) {
  if (!menuId) {
    return
  }

  const params = {
    menuId: menuId,
  }
  //权限加载
  getResourcesAll(params).then((resp) => {
    if (resp) {
      let data = resp.data.map((it) => {
        let isSelectPrintDialogVisible = !!(it.code.indexOf(':print') !== -1)
        return {
          ...it,
          isSelectPrintDialogVisible,
        }
      })
      state.resourceList = data
    }
  })
}
function _getMenuDetail(id, parentName) {
  getMenuDetail(id).then((resp) => {
    console.log('resp', resp)
    if (resp.success) {
      resp.data.parentName = parentName
      state.menuDetailData = resp.data
      console.log(state.menuDetailData)
      state.status = state.menuDetailData.status
      state.nodeId = {
        menuId: resp.data.id,
        resourceDesc: resp.data.name,
        // resourceCode: resp.data.resourceCode
      }
    }
  })
}
function handleNodeClick(node, data) {
  console.log('1', node, data)
  //查看菜单详情
  proxy.$refs['ruleForm'].resetFields()
  state.saveBtn = false
  state.addOrUpdate = 'update'
  state.checkedMenuId = node.id
  state.checkedMenuCode = node.code
  if (node.id !== '-1') {
    state.validate = false
    if (node.code === 'app' || node.code === 'pda') {
      state.deleteBtn = true
    } else {
      state.deleteBtn = false
    }
    state.addBtn = false
    let parentName = data.parent.data.name
    _getMenuDetail(node.id, parentName)
    state.menuNodeId = node.id
    if (node.href !== '' && node.href !== null) {
      state.resourcesPanelShow = true
      loadResource(node.id)
    } else {
      state.resourcesPanelShow = false
    }
  } else {
    state.menuDetailData = {}
    state.resourcesPanelShow = false
    state.validate = true
    state.deleteBtn = true
    state.addBtn = true
    state.resourceList = []
  }
}
</script>

<style lang="scss" scoped>
.main-flex {
  flex-grow: 1;
  display: flex;
  flex-wrap: nowrap;
  height: calc(100% - 51px);
  .el-tree {
    width: 100%;
    padding: 0 20px 20px;
    overflow-y: auto;
  }
}
.textaea {
  width: 63.6%;
}
</style>
